package com.xiaobai.demo.controller;

import com.xiaobai.demo.pojo.LoginRequest;
import com.xiaobai.demo.pojo.User;
import com.xiaobai.demo.service.UserService;
import com.xiaobai.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    // 注册用户
    @PostMapping("/register")
    public Result register(@Valid @RequestBody User user) {
        boolean result = userService.register(user);
        if (result) {
            return Result.success("注册成功", "注册成功");
        } else {
            return Result.failure(500, "注册失败");
        }
    }

    // 登录验证
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        String userName = loginRequest.getUserName();
        String password = loginRequest.getPassword();
        User user = userService.login(userName, password);
        if (user != null) {
            return Result.success(user,"登录成功");
        } else {
            return Result.failure(401, "用户名或密码错误");
        }
    }

    // 查询所有用户
    @GetMapping
    public Result findAll() {
        List<User> users = userService.findAll();
        return Result.success(users,"查询成功");
    }

    // 根据 id 查询用户
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        if (user != null) {
            return Result.success(user,"查询成功");
        } else {
            return Result.failure(404, "用户不存在");
        }
    }

    // 根据用户名模糊查询用户
    @GetMapping("/search")
    public Result findByUserNameLike(@RequestParam String userName) {
        List<User> users = userService.findByUserNameLike(userName);
        return Result.success(users,"查询成功");
    }

    // 更新用户信息
    @PutMapping
    public Result update(@Valid @RequestBody User user) {
        boolean result = userService.update(user);
        if (result) {
            return Result.success("更新成功", "更新成功");
        } else {
            return Result.failure(500, "更新失败");
        }
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean result = userService.delete(id);
        if (result) {
            return Result.success("删除成功", "删除成功");
        } else {
            return Result.failure(500, "删除失败");
        }
    }
}